/*
 * N900Resolve.cpp
 *
 *  Created on: Aug 30, 2016
 *      Author: ubuntu
 */

#include "N900Resolve.h"
#include <unistd.h>
#include "../common.h"
#include "../Conf.h"

using namespace std;

N900Resolve::N900Resolve()
{
	m_bTerminated = false;
	m_pDBPool = getConf()->cpool;
	pthread_mutex_init(&m_summa_mutex, NULL);
}

N900Resolve::~N900Resolve()
{
	pthread_mutex_destroy(&m_summa_mutex);
}

void N900Resolve::push(N900Summary *pSummary)
{
	pthread_mutex_lock(&m_summa_mutex);
	m_lstSummary.push(pSummary);
	pthread_mutex_unlock(&m_summa_mutex);
}

void N900Resolve::stop()
{
	m_bTerminated = true;
}

void N900Resolve::run()
{
	if (m_pDBPool == NULL) {
		debug(LOG_DEBUG, "数据库线程池错误");
		stop();
	}
	while (!m_bTerminated) {
		if (m_lstSummary.empty()) {
			usleep(1000);
			continue;
		}
		N900Summary *pSummary = NULL;
		pthread_mutex_lock(&m_summa_mutex);
		if (!m_lstSummary.empty()) {
			pSummary = m_lstSummary.front();
			m_lstSummary.pop();
		}
		pthread_mutex_unlock(&m_summa_mutex);
		if (pSummary) {
			pSummary->parse();
			writeDB(pSummary);
			delete pSummary;
		}
	}
}

void N900Resolve::writeDB(N900Summary *pSummary)
{
	Connection *pConn = m_pDBPool->grab();
	if (pConn) {
rewrite:
		try {
			pSummary->writeDB(pConn);
		} catch (mysqlpp::BadQuery &er) {
			if (er.errnum() == 1146) {
				pSummary->createTB(pConn);
				goto rewrite;
			}
			debug(LOG_DEBUG, "Query error: %s", er.what());
		}
		m_pDBPool->release(pConn);
	}
}

void N900Resolve::getBuf(unsigned char *buf, size_t len)
{
	N900Summary *pSummary = new N900Summary();
	pSummary->getBuf(buf, len);
	push(pSummary);
}
